package com.crm.controller;

import com.crm.annotation.PassToken;
import com.crm.constant.dto.BaseFxResponse;
import com.crm.constant.dto.ResultCode;
import com.crm.constant.enums.FileTypeEnum;
import com.crm.utils.CrmFileUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @version 1.0
 * @author: CRM_SYSTEM
 * @date: 2022/3/31 19:22
 * @Description:
 */
@RestController
@RequestMapping("/crm-site")
public class FileController {

    @PassToken
    @ApiOperation("上传附件")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public BaseFxResponse<String> uploadFile(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename = CrmFileUtils.getFileName(filename);
        FileTypeEnum fileTypeEnum = FileTypeEnum.getBySuffix(suffix);
        String filePath = CrmFileUtils.getUploadPath(fileTypeEnum, filename);
        filePath = filePath + File.separator + filename;
        if (!file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
                out.write(file.getBytes());
                out.flush();
                return BaseFxResponse.success(filePath);
            } catch (Exception e) {
                e.printStackTrace();
                return BaseFxResponse.fail(ResultCode.EXCEPTION_FILE_FAIL);
            }
        } else {
            return BaseFxResponse.fail(ResultCode.EXCEPTION_FILE_NOT_EXIST);
        }
    }

    @PassToken
    @ApiOperation("下载附件")
    @RequestMapping(value = "/downLoadFile", method = RequestMethod.POST)
    public BaseFxResponse<?> downLoadFile(@RequestParam("fileUrl") MultipartFile fileUrl) {
        return BaseFxResponse.success();
    }

    public static void main(String[] args) {
        String s = "1231.png";
        String substring = s.substring(s.lastIndexOf("."));
        System.out.println(substring);
    }
}
